package com.kim.bookshop.order.action;

import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;

import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts2.ServletActionContext;
import org.springframework.context.ApplicationContext;

import com.kim.bookshop.cart.bean.Cart;
import com.kim.bookshop.cart.bean.CartItem;
import com.kim.bookshop.order.bean.Order;
import com.kim.bookshop.order.bean.OrderItem;
import com.kim.bookshop.order.service.OrderService;
import com.kim.bookshop.user.bean.User;
import com.kim.bookshop.util.PaymentUtil;
import com.opensymphony.xwork2.ActionSupport;

import cn.itcast.commons.CommonUtils;
import exception.BookShopException;

public class OrderAction extends ActionSupport{

	private static final long serialVersionUID = 1516731337384216937L;
	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	private ServletContext application;
	private ApplicationContext ctx;	
	private OrderService orderService;
	
	public OrderAction(){
		request=ServletActionContext.getRequest();
		response=ServletActionContext.getResponse();
		session=request.getSession();
		application= session.getServletContext();
		ctx=(ApplicationContext) application.getAttribute("ApplicationContext"); 
		orderService=(OrderService) ctx.getBean("orderService");
	}
	
	/**
	 * 添加订单
	 * @return
	 */
	public String add(){
		Cart cart=(Cart) session.getAttribute("cart");
		Order order=new Order();
		order.setOid(CommonUtils.uuid());
		order.setOrdertime(new Date());
		order.setState(1);
		User user=(User) session.getAttribute("user");
		order.setOwner(user);
		order.setTotal(cart.getTotal());
		
		//订单条目集合
		List<OrderItem> orderItemList = new ArrayList<OrderItem>();
		for (CartItem cartItem:cart.getCartItems()) {
			OrderItem oi=new OrderItem();
			oi.setIid(CommonUtils.uuid());
			oi.setCount(cartItem.getCount());
			oi.setBook(cartItem.getBook());
			oi.setSubtotal(cartItem.getSubtotal());
			oi.setOrder(order);
			
			orderItemList.add(oi);
		}
		order.setOrderItemList(orderItemList);
		cart.clear();
		orderService.addOrder(order);
		request.setAttribute("order", order);
		
		return SUCCESS;
	}
	
	/**
	 * 我的订单
	 * 按照当前用户查询
	 * @return
	 */
	public String myorder(){
		User user=(User) session.getAttribute("user");
		List<Order> orderList=orderService.myOrders(user.getUid());
		request.setAttribute("orderList", orderList);
		return "myorder";
	}
	
	/**
	 * 加载订单
	 * @return
	 */
	public String load(){
		request.setAttribute("order",orderService.load(request.getParameter("oid")));
		return SUCCESS;
	}
	
	public String deliver(){
		String oid=request.getParameter("oid");
		try {
			orderService.deliver(oid);
			return "deliver";
		} catch (BookShopException e) {
			e.printStackTrace();
			return "msg";
		}
	}
	
	/**
	 * 确认订单
	 * @return
	 */
	public String confirm(){
		String oid=request.getParameter("oid");
		try {
			orderService.confirm(oid);
			request.setAttribute("msg", "交易成功");
			return "myorder";
		} catch (BookShopException e) {
			request.setAttribute("msg", e.getMessage());
			return "myorder";
		}
	}
	
	/**
	 * 订单支付
	 * 易宝13参数
	 * 重定向到易宝
	 * @return
	 * @throws IOException
	 */
	public String pay() throws IOException{
		Properties props=new Properties();
		InputStream input=this.getClass().getClassLoader()
						.getResourceAsStream("merchantInfo.properties");
		props.load(input);
		
		//13参数
		String p0_Cmd = "Buy";
		String p1_MerId = props.getProperty("p1_MerId");
		String p2_Order = request.getParameter("oid");
		String p3_Amt = "0.01";
		String p4_Cur = "CNY";
		String p5_Pid = "";
		String p6_Pcat = "";
		String p7_Pdesc = "";
		String p8_Url = props.getProperty("p8_Url");
		String p9_SAF = "";
		String pa_MP = "";
		String pd_FrpId = request.getParameter("pd_FrpId");
		String pr_NeedResponse = "1";
		
		//计算hmac
		String keyValue = props.getProperty("keyValue");
		String hmac = PaymentUtil.buildHmac(p0_Cmd, p1_MerId, p2_Order, p3_Amt,
				p4_Cur, p5_Pid, p6_Pcat, p7_Pdesc, p8_Url, p9_SAF, pa_MP,
				pd_FrpId, pr_NeedResponse, keyValue);
		
		//连接易宝的网址和13+1个参数
		StringBuilder url = new StringBuilder(props.getProperty("url"));
		url.append("?p0_Cmd=").append(p0_Cmd);
		url.append("&p1_MerId=").append(p1_MerId);
		url.append("&p2_Order=").append(p2_Order);
		url.append("&p3_Amt=").append(p3_Amt);
		url.append("&p4_Cur=").append(p4_Cur);
		url.append("&p5_Pid=").append(p5_Pid);
		url.append("&p6_Pcat=").append(p6_Pcat);
		url.append("&p7_Pdesc=").append(p7_Pdesc);
		url.append("&p8_Url=").append(p8_Url);
		url.append("&p9_SAF=").append(p9_SAF);
		url.append("&pa_MP=").append(pa_MP);
		url.append("&pd_FrpId=").append(pd_FrpId);
		url.append("&pr_NeedResponse=").append(pr_NeedResponse);
		url.append("&hmac=").append(hmac);

		System.out.println(url.toString());
		
		//重定向到易宝
		response.sendRedirect(url.toString());
		
		return null;
	}
	
	/**
	 * 支付回调方法
	 * @return
	 * @throws IOException 
	 */
	public String back() throws IOException{
		//获取11+1参数
		String p1_MerId = request.getParameter("p1_MerId");
		String r0_Cmd = request.getParameter("r0_Cmd");
		String r1_Code = request.getParameter("r1_Code");
		String r2_TrxId = request.getParameter("r2_TrxId");
		String r3_Amt = request.getParameter("r3_Amt");
		String r4_Cur = request.getParameter("r4_Cur");
		String r5_Pid = request.getParameter("r5_Pid");
		String r6_Order = request.getParameter("r6_Order");
		String r7_Uid = request.getParameter("r7_Uid");
		String r8_MP = request.getParameter("r8_MP");
		String r9_BType = request.getParameter("r9_BType");
		
		String hmac = request.getParameter("hmac");
		
		//校验访问者是否为易宝！
		Properties props = new Properties();
		InputStream input = this.getClass().getClassLoader()
				.getResourceAsStream("merchantInfo.properties");
		props.load(input);
		String keyValue = props.getProperty("keyValue");
		
		boolean bool=PaymentUtil.verifyCallback(hmac, p1_MerId, r0_Cmd, r1_Code, r2_TrxId, r3_Amt, r4_Cur, r5_Pid, r6_Order, r7_Uid, r8_MP, r9_BType, keyValue);
		
		if(!bool){//校验失败
			request.setAttribute("msg", "违规操作！");
			return "msg";
		}
		//获取状态订单，确定是否要修改订单状态，以及等业务操作
		orderService.pay(r6_Order);//有可能对数据库进行操作，也可能不操作
		
		//判断当前回调方式 若为点对点，需要回馈已success开头得字符串
		
		if(r9_BType.equals("2")){
			response.getWriter().println("success");
		}
		
		//保存成功信息，转发到msg.jsp
		//request.setAttribute("msg", "支付成功！等待卖家发货");
		return "myorder";
	}
	
	/**
	 * 所有订单
	 * @return
	 * @throws Exception
	 */
	public String list() throws Exception {
		request.setAttribute("orderList", orderService.findAll());
		return SUCCESS;
	}
	
	/**
	 * 未付款订单
	 * @return
	 * @throws Exception
	 */
	public String unpaid() throws Exception {
		request.setAttribute("orderList", orderService.unpayorder());
		return SUCCESS;
	}
	
	/**
	 * 已付款订单
	 * @return
	 * @throws Exception
	 */
	public String paid() throws Exception {
		request.setAttribute("orderList", orderService.paidorder());
		return SUCCESS;
	}
	
	/**
	 * 未确认订单
	 * @return
	 * @throws Exception
	 */
	public String unconfirm() throws Exception {
		request.setAttribute("orderList", orderService.unconfirm());
		return SUCCESS;
	}
	
	/**
	 * 交易成功订单
	 * @return
	 * @throws Exception
	 */
	public String success() throws Exception {
		request.setAttribute("orderList", orderService.success());
		return SUCCESS;
	}
}
